import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    cachedViews: [],
    routers: []
  },
  mutations: {
    SETNAV: (state, data) => {
      state.routers = data
    },
    ADD_CACHED_VIEW: (state, view) => {
      if (state.cachedViews.includes(view.name)) return
      if (!view.meta.noCache) {
        state.cachedViews.push(view.name)
      }
    },
    DEL_CACHED_VIEW: (state, view) => {
      for (const i of state.cachedViews) {
        if (i === view.name) {
          const index = state.cachedViews.indexOf(i)
          state.cachedViews.splice(index, 1)
          break
        }
      }
    }
  },
  actions: {
    SETNAV({ commit }, data) {
      console.log('action---', data)
      commit('SETNAV', data)
    },
    addView({ dispatch }, view) {
      const tempView = {
        fullPath: view.fullPath,
        meta: view.meta,
        name: view.name,
        params: view.params,
        path: view.path,
        query: view.query
      }
      dispatch('addCachedView', tempView)
    },
    addCachedView({ commit }, view) {
      commit('ADD_CACHED_VIEW', view)
    },
    delCachedView({ commit, state }, view) {
      return new Promise((resolve) => {
        commit('DEL_CACHED_VIEW', view)
        resolve([...state.cachedViews])
      })
    }
  },
  modules: {
  }
})
